package com.springapp.symm.controller;

import com.springapp.jgit.App;
import com.springapp.symm.bean.DetailedPOJO;
import com.springapp.symm.service.GithubManager;
import com.springapp.utils.GlobalUtils;
import com.springapp.utils.FileTools;
import org.markdown4j.Markdown4jProcessor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Tandan
 * @Date 17-3-23
 * @see
 */
@Controller
@RequestMapping("/DetailedCon")
public class DetailedCon {

    @RequestMapping(value = {"index",""})
    public String selDetailedPage(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws  Exception {
        List<DetailedPOJO> list = new ArrayList<DetailedPOJO>();

        String catalog = request.getParameter("Catalog");
        String templatesType = request.getParameter("templatesType");
        String path = GlobalUtils.getBasePath()+ File.separator + templatesType + File.separator + catalog ; //GlobalUtils.getFullPath() + File.separator + catalog;
        list = new IndexCon().getVerion(path);

        //sds

        //config.xml
        String configyml = "";
        if( FileTools.judgeIsFileExist(path+File.separator+"config.yml",false) ){
            configyml = FileTools.readTxtFile( path+File.separator+"config.yml" );
            configyml =  new Markdown4jProcessor().process(configyml);
            if(configyml.indexOf("description") < configyml.indexOf("version") ) {
                configyml = configyml.substring(configyml.indexOf("description"), configyml.indexOf("version"));
            }else if( configyml.indexOf("description") < configyml.indexOf("projectURL")){
                configyml = configyml.substring(configyml.indexOf("description"), configyml.indexOf("projectURL"));
            }
        }
        //image path
        String imagePath  = "";
        File svgFile  = new File ( path );
        File[] svgFiles = svgFile.listFiles();
        for(int j = 0; j < svgFiles.length; j++){
            if(svgFiles[j].getName().indexOf("catalogIcon")>=0){
                imagePath = GlobalUtils.getProjectName()  + File.separator + templatesType +  File.separator  + catalog + File.separator  + svgFiles[j].getName();
            }
        }

        model.addAttribute("list",list);
        model.addAttribute("configyml",configyml);
        model.addAttribute("imagePath",imagePath);
        model.addAttribute("catalog",catalog);
        model.addAttribute("templatesType",templatesType);
        return "DetailedCon";
    }

    @RequestMapping(value = {"save"})
    public String saveEle(ModelMap model, HttpServletRequest request, HttpServletResponse response) {

        Map map = new HashMap();
        String result = "success";
        String desc= "";

        try {
            String catalog = request.getParameter("catalog");
            String version = request.getParameter("version");
            String filename = request.getParameter("filename");
            String contexts = request.getParameter("contexts");
            String templatesType = request.getParameter("templatesType");
            if("dockerCompose".equals(filename)){
                filename ="docker-compose.yml";
            }else{
                filename = "rancher-compose.yml";
            }

            String fullPath = GlobalUtils.getBasePath()  + File.separator + templatesType + File.separator + catalog + File.separator +  version
                    + File.separator + filename;

            FileTools.StringBufferWrite(fullPath,contexts);

            //执行目录提交命令
            //new App().commitRepository(GlobalUtils.getBasePath() , ".","jgit commit");
            //new App().pushRepository(GlobalUtils.getBasePath() );
            new GithubManager().updateFile();//update git
            desc = "保存成功";
        } catch (Exception e) {
            e.printStackTrace();
            result="fail";
            desc="出现异常,请联系客服; 异常:"+e.toString();
        }

        ModelAndView modelView = new ModelAndView();
        map.put("result",result);
        map.put("desc",desc);
        modelView.addAllObjects(map);

        print(response, result);
        return null ;
    }


    @RequestMapping(value = {"versionDelete"})
    public String versionDelete(ModelMap model, HttpServletRequest request, HttpServletResponse response) {

        Map map = new HashMap();
        String result = "success";
        String desc= "";

        try {
            String catalog = request.getParameter("catalog");
            String version = request.getParameter("version");
            String templatesType = request.getParameter("templatesType");


            String fullPath = GlobalUtils.getBasePath()  + File.separator + templatesType + File.separator + catalog + File.separator + version;

            boolean bl = FileTools.deleteDirectory(fullPath);

            //执行目录提交命令
            //new App().commitRepository(GlobalUtils.getBasePath() , ".","jgit commit");
            //new App().pushRepository(GlobalUtils.getBasePath() )
            if(bl){
                // new GithubManager().removeFile( templatesType + "/" + catalog );
                new GithubManager().removeFile(templatesType + "/" + catalog + "/" + version);//update git
                desc = "删除版本成功";
            }else{
                desc = "删除失败，请重新更新此项目或者联系管理人员";
            }


        } catch (Exception e) {
            e.printStackTrace();
            result="fail";
            desc="出现异常,请联系客服; 异常:"+e.toString();
        }

        ModelAndView modelView = new ModelAndView();
        map.put("result",result);
        map.put("desc",desc);
        modelView.addAllObjects(map);

        print(response, result);
        return null ;
    }

    public void print(HttpServletResponse response, String content) {
        try {

            response.setContentType("text/html; charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            PrintWriter write = response.getWriter();
            write.print(content);
            write.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}